#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os
import binascii
import argparse


#----- Variables Globales -----

fcontents = None
fileName = None
start = None
lenght = None


#------------------------------


def usage():
    print sys.argv[1:]
    #print "asdf"
    quit()


#------------------------------------------------------------------------------------------
parser = argparse.ArgumentParser(description='This is a python Free Space Finder')

group = parser.add_argument_group('required arguments')

group.add_argument('-r', '--rom', type=str, #action="store",# nargs='1',
                   help='rom filename', required=True)
group.add_argument('-o', '--offset', type=str,# nargs='1',
                   help='rom offset', required=True)
group.add_argument('-l', '--length', type=str,# nargs='1',
                   help='wanted length', required=True)


args = parser.parse_args()
fileName = args.rom
start = args.offset
lenght = args.lenght


#------------------------------------------------------------------------------------------


def elegir_ROM():
    global fileName
    if (len(sys.argv) > 1):
        fileName = sys.argv[1]
    else:
        fileName = raw_input("Introduce la ruta hasta el ROM: ")


def abrir_ROM():
    global fcontents
    global fileName
    f = open(fileName, "rb")
    fcontents = f.read()
    f.close()

def conv_a2h(asciistr):
    hexstr = binascii.b2a_hex(asciistr)
    return hexstr

def convn_h2a(hexstr):
    asciistr = binascii.b2a_hex(hexstr)
    return asciistr

def conv_dec2hex(decnum):
    hexnum = hex(decnum)[2:]
    return hexnum

def conv_hex2dec(hexnum):
    decnum = int(str(hexnum), 16)
    return decnum

def buscar(byte,lenght,start):
    global fcontents
    sub = byte * lenght
    offset_found = fcontents.find(sub, start*2) / 2
    if offset_found == -1:
        return "Not found"
    else:
        return offset_found
    

def main():
    global fcontents
    global lenght
    abrir_ROM()
    fcontents = convn_h2a(fcontents)
    #print fcontents
    found = buscar("ff",conv_hex2dec(lenght),conv_hex2dec(start))
    if found != "Not found":
        found = conv_dec2hex(found)
        print "Space with " + str(lenght) + " FF's found in offset " + found
    else:
        print "Space with " + str(lenght) + " FF's " + found
    

if __name__ == '__main__':
	main()



